package com.ftwj.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftwj.entity.SysMenu;
import com.ftwj.mapper.SysMenuMapper;
import com.ftwj.mapper.SysUserMapper;
import com.ftwj.service.SysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Override
    public boolean addParentMenu(SysMenu menu) {
        // 校验path和menuName是否为空
        if (StringUtils.isBlank(menu.getPath()) || StringUtils.isBlank(menu.getMenuName())) {
            throw new IllegalArgumentException("路径(path)和菜单名称(menuName)必须填写");
        }
        // 校验menuName是否重复
        SysMenu existingMenu = sysMenuMapper.selectByMenuName(menu.getMenuName());        if (existingMenu != null) {
            throw new IllegalStateException("菜单名称已存在");
        }
        menu.setParentId("0"); // 确保父菜单的parentId为空
        menu.setCreateTime(DateTime.now());
        menu.setUpdateTime(DateTime.now());
        menu.setState(1);
        return sysMenuMapper.insert(menu)>0? true : false ;
    }

    @Override
    public boolean addChildren(String id, SysMenu menu) {
        SysMenu parent = this.getById(id);
        if (StringUtils.isBlank(menu.getPath()) || StringUtils.isBlank(menu.getMenuName())) {
            throw new IllegalArgumentException("路径(path)和菜单名称(menuName)必须填写");
        }
        // 校验menuName是否重复
        SysMenu existingMenu = sysMenuMapper.selectByMenuName(menu.getMenuName());        if (existingMenu != null) {
            throw new IllegalStateException("菜单名称已存在");
        }
        if (parent != null) {
            menu.setParentId(parent.getId());
            menu.setCreateTime(DateTime.now());
            menu.setUpdateTime(DateTime.now());
            menu.setState(1);
            return super.save(menu);
        }
        return false;
    }

    @Override
    public List<SysMenu> getParentMenus() {

        return this.list(new QueryWrapper<SysMenu>().eq("parent_id", "0"));
    }

    @Override
    public List<SysMenu> findMenuByMenuName(String menuName) {
        return sysMenuMapper.findMenuByMenuName(menuName);
    }
}
